package com.company.eos.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.company.eos.mapper.AuditExpenseMapper;
import com.company.eos.mapper.AuditFlowMapper;
import com.company.eos.domain.AuditExpense;
import com.company.eos.service.AuditDetailService;
import com.company.eos.service.AuditExpenseService;
import com.company.eos.service.AuditFlowService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.company.eos.common.util.PageUtils;
import com.company.eos.common.R;
import com.company.eos.controller.form.reim.DeleteReimByIdForm;
import com.company.eos.controller.form.reim.InsertReimForm;
import com.company.eos.controller.form.reim.SearchReimByIdForm;
import com.company.eos.controller.form.reim.SearchReimByPageForm;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.HashMap;

/**
 * @author: Song, Wei
 * @date: 2022-04-09
 */
@Slf4j
@RestController
@RequestMapping("/reim")
@Tag(name = "报销模块Web接口")
public class AuditExpenseController {

    @Autowired
    private AuditExpenseService expenseService;
    @Autowired
    private AuditFlowService auditFlowService;
    @Autowired
    private AuditDetailService auditDetailService;
    @Resource
    private AuditFlowMapper auditFlowMapper;
    @Resource
    private AuditExpenseMapper auditExpenseMapper;

    @PostMapping("/searchReimByPage")
    @Operation(summary = "查询报销分页记录")
    @SaCheckLogin
    public R searchReimByPage(@Valid @RequestBody SearchReimByPageForm form) {
        log.info("查询报销分页记录，参数：{}", form);
        @NotNull(message = "page不能为空") @Min(value = 1, message = "page不能小于1") Integer page = form.getPage();
        @NotNull(message = "length不能为空") @Range(min = 10, max = 50, message = "length必须在10~50之间") Integer length = form.getLength();
        int start = (page - 1) * length;
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        param.put("start", start);
        param.put("currentUserId", StpUtil.getLoginIdAsInt());
        if (!(StpUtil.hasPermission("REIM:SELECT")) || StpUtil.hasPermission("ROOT")) {
            param.put("userId", StpUtil.getLoginIdAsInt());
        }
        PageUtils pageUtils = expenseService.searchExpenseByPage(param);
        return R.ok().put("page", pageUtils);
    }

    @PostMapping("/insert")
    @Operation(summary = "添加报销申请")
    @SaCheckLogin
    public R insert(@Valid @RequestBody InsertReimForm form) {
        log.info("添加报销申请，参数：{}", form);
        if (!JSONUtil.isJsonArray(form.getContent())) {
            return R.error("content不是json数组");
        }
        AuditExpense expense = JSONUtil.parse(form).toBean(AuditExpense.class);
        expense.setUserId(StpUtil.getLoginIdAsInt());
        expense.setStatus(1);
        // 向流程表中添加报销申请
        int i = auditFlowService.insertExpenseAudit(expense);
        auditDetailService.insertAuditExpense(expense, auditFlowMapper.selectById(i));
        expense.setFlowId(i);
        // 向报销表中插入报销的相关信息
        int rows = expenseService.insert(expense);
        return R.ok().put("rows", rows);
    }

    @PostMapping("/searchReimById")
    @Operation(summary = "根据ID查询报销单详情")
    @SaCheckLogin
    public R searchReimById(@Valid @RequestBody SearchReimByIdForm form) {
        log.info("根据ID查询报销单详情，参数：{}", form);
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        if (!(StpUtil.hasPermission("REIM:SELECT")) || StpUtil.hasPermission("ROOT")) {
            param.put("userId", StpUtil.getLoginIdAsInt());
        }
        HashMap map = expenseService.searchExpenseById(param);
        return R.ok(map);
    }

    @PostMapping("/deleteReimById")
    @Operation(summary = "删除报销记录")
    @SaCheckLogin
    public R deleteReimById(@Valid @RequestBody DeleteReimByIdForm form) {
        log.info("删除报销记录，参数：{}", form);
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        param.put("userId", StpUtil.getLoginIdAsInt());
        int rows = expenseService.deleteExpenseById(param);
        // 删除流程表中的报销申请记录
        AuditExpense expense = auditExpenseMapper.selectById(form.getId());
        auditDetailService.deleteAudit(expense.getFlowId());
        return R.ok().put("rows", rows);
    }

}
